﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TLWindowsEditorWinFormsDemo
{
    /// <summary>
    /// 本地化服务
    /// by IT_MAOFY 2024/08/14
    /// 调用示例：
    /// 1.LocalizationService.Instance.GetText('The Machine No:');
    /// 2.LocalizationService.Instance.GetText('The Machine No:','zh_TW');
    /// </summary>
    public class LocalizationService
    {
        private static LocalizationInfo _list = new LocalizationInfo();
        private static string _fileName = "Localization.xml";
        private static string _doc = "Doc";
        private static bool _isInit = false;

        private static readonly LocalizationService _instance;

        static LocalizationService()
        {
            _instance = new LocalizationService();
        
        }

        private LocalizationService() { }

        public static LocalizationService Instance
        {
            get
            {
                return _instance;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private static void Init()
        {
            if (_isInit == true) 
            {
                return;
            }
            _isInit = true;
            var xml = DocHelper.GetContent(_fileName, _doc);
            _list = XmlHelper.Deserialize<LocalizationInfo>(xml);
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="languageCode"></param>
        /// <param name="doc"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string GetText(string key, string languageCode = "zh_CN")
        {
            Init();
            if (_list == null)
            {
                return key;
            }
            var currentItem = _list.ItemGroup?
                    .FirstOrDefault(m => m.type?.ToUpper() == languageCode?.ToUpper())?
                    .Message?
                    .FirstOrDefault(m => m.Name == key);
            if (currentItem == null || string.IsNullOrEmpty(currentItem.Value))
            {
                return key;
            }
            return currentItem.Value;
        }
    }
}
